package com.alliky.user.ui.fragment

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadState
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alliky.common.router.RoutePath
import com.alliky.core.base.BaseFragment
import com.alliky.user.R
import com.alliky.user.databinding.FragmentMyBinding
import com.alliky.user.ui.adapter.RecommendAdapter
import com.alliky.user.ui.viewmodel.MyViewModel
import kotlinx.android.synthetic.main.fragment_my.*
import kotlinx.coroutines.flow.collectLatest

@ExperimentalPagingApi
@Route(path = RoutePath.User.MyFragment)
class MyFragment : BaseFragment<FragmentMyBinding>() {


    private val mViewModel: MyViewModel by activityViewModels()

    private val mRecommendAdapter: RecommendAdapter = RecommendAdapter()

    override fun getLayoutId(): Int {
        return R.layout.fragment_my
    }

    override fun initData(savedInstanceState: Bundle?) {
        mBinding.recyclerViewRecommend.apply {
            layoutManager = GridLayoutManager(requireContext(), 2)
            adapter = mRecommendAdapter
        }
        mBinding.refreshLayout.setOnRefreshListener {
            refreshLayout.postDelayed({
                mRecommendAdapter.refresh()
            }, 500)
        }

        lifecycleScope.launchWhenCreated {
            mRecommendAdapter.loadStateFlow.collectLatest {
                mBinding.refreshLayout.isRefreshing = it.refresh is LoadState.Loading
            }
        }

        lifecycleScope.launchWhenCreated {
            mViewModel.recommondPagingFlow().collectLatest { data ->
                mRecommendAdapter!!.submitData(data)
            }
        }
    }

    override fun initObservable() {

    }

}